/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pianoinhand.canvas;

/**
 *
 * @author GiaThuy
 */
import java.io.IOException;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class Button extends View {

    public final static int BUTTON_NORMAL = 0;
    public final static int BUTTON_PRESSED = 1;
    private static final int TEXT_COLOR = 0x00000000;
    private static final int TEXT_PRESSED_COLOR = 0x00ff0000;
    private static final int BACK = 0x00221f1f;
    private String text = "";
    private volatile int state = BUTTON_NORMAL;
    private final Listener listener;
    private Image imageBackground = null;

    public Button(String text, Listener listener) {
        super();
        this.text = text;
        this.listener = listener;

    }

    protected void paint(Graphics g) {
        /*try {
         imageBackground = ReSize.resize(Image.createImage("/about.png"), width, height);
         } catch (IOException ex) {
         ex.printStackTrace();
         }*/
        g.setColor(BACK);
//        g.fillRoundRect(left, top, width, height, width, height - 15);        
        g.drawImage(this.img, left, top, 0);
        int c = TEXT_COLOR;
        switch (state) {
            case BUTTON_PRESSED:
                
                c = TEXT_PRESSED_COLOR;
                break;
            default:
                break;
        }
        g.setColor(c);
        final Font f = g.getFont();
        g.drawString(text, left + width / 2,
                top + height / 2 - f.getHeight() / 2,
                Graphics.HCENTER | Graphics.TOP);
    }

    public void handlePointerEvent(int type, int x, int y) {
        if (!isVisible()) {
            return;
        }
        if (hits(x, y)) {
            changeState(type == View.POINTER_RELEASED ? BUTTON_NORMAL : BUTTON_PRESSED);
            
            if (type == View.POINTER_RELEASED) {
                listener.onClick(this);
            }
        } else if (type == View.POINTER_DRAGGED) {
            changeState(BUTTON_NORMAL);
        }
    }

    private void changeState(int newState) {
        if (state != newState) {
            invalidate();
        }
        state = newState;
    }

    public void keyEvent(int type) {
        if (type == KEY_RELEASED) {
            changeState(BUTTON_NORMAL);
            listener.onClick(this);
        } else {
            changeState(BUTTON_PRESSED);
        }
    }

    public static interface Listener {

        void onClick(Button b);
    }
}
